﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace yysAuxiliary
{
    public partial class MainFrm : Form
    {
        public MainFrm()
        {
            InitializeComponent();
        }
        private void MainFrm_Load(object sender, EventArgs e)
        {
            AuthFrm loginFrm = new AuthFrm();
            if (loginFrm.ShowDialog() == DialogResult.OK)
            {
                refreshTime.Start();
                lbAuthTime.Text = Data.AuthExpireTime.ToString("D") + "过期";
                //加载配置数据 
                cbType.DataSource = BindComboxEnumType<SimulatorType>.BindTyps;
                cbType.DisplayMember = "Name";
                cbType.ValueMember = "Type";
                cbType.SelectedIndexChanged += cbType_SelectedIndexChanged;
                cbType.SelectedValue = ConfigData.Current.Type;
                WNum.Value = ConfigData.Current.SimulatorSize.Width;
                HNum.Value = ConfigData.Current.SimulatorSize.Height;
            }
            else
            {
                MessageBox.Show("授权失败，程序关闭");
                this.Close();
            }
        }


        /// <summary>
        /// 获取进程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                WinHelper.winIntPtr = Convert.ToInt32(txtName.Text.Trim());
                pictureBox1.Image = WinHelper.GetBitmap();
                btnClick.Enabled = true;
                btnKS.Enabled = true;
                btnSetSize.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }


        /// <summary>
        /// 开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnKS_Click(object sender, EventArgs e)
        {

            if (btnKS.Text == "开始")
            {
                if (!Init())
                    return;
                Data.isRun = true;
                btnStart.Enabled = false;
                butSelect.Enabled = false;
                gbSelectAction.Enabled = false;
                btnKS.Text = "结束";
                Data.IndexLoop = 1;
                Data.tokenSource = new CancellationTokenSource();
                await Task.Run(async () =>
                {
                    PicHandle pic = new PicHandle(WriteMsg, Data.tokenSource.Token);
                    await pic.Execute();
                    btnKS.Invoke(new Action(() =>
                    {
                        btnKS.Text = "开始";
                        btnKS.Enabled = true;
                    }));
                    gbSelectAction.Invoke(new Action(() =>
                    {
                        gbSelectAction.Enabled = true;
                    }));
                }, Data.tokenSource.Token);
            }
            else
            {
                btnKS.Enabled = false;
                Data.isRun = false;
                btnKS.Text = "结束中...";
                Data.tokenSource.Cancel();
            }
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        private bool Init()
        {
            Data.fsList.Clear();
            Data.actionedList.Clear();
            #region 功能
            //御灵
            if (ckbYL.Checked)
                Data.fsList.Add(new FSConfig { fs = Data.FS.YL, Count = 30 });
            //御魂
            if (ckbYH.Checked)
                Data.fsList.Add(new FSConfig { fs = Data.FS.YH, Count = Convert.ToInt32(numYH.Value) });
            //结界突破
            if (ckbJJTP.Checked)
                Data.fsList.Add(new FSConfig { fs = Data.FS.JJTP });
            //业原火
            if (ckbYYH.Checked)
                Data.fsList.Add(new FSConfig { fs = Data.FS.YYH, Count = Convert.ToInt32(numYYH.Value) });
            #endregion
            if (Data.fsList.Count == 0)
            {
                WriteMsg("没有选择功能");
                return false;
            }
            Random r = new Random();
            FSConfig needAction = Data.fsList[r.Next(Data.fsList.Count)];
            Data.IndexFS = needAction;
            return true;
        }

        /// <summary>
        /// 模拟点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClick_Click(object sender, EventArgs e)
        {
            WinHelper.SendCheck(new Point((int)Xnum.Value, (int)Ynum.Value));
            pictureBox1.Image = WinHelper.GetBitmap();
        }



        MouseHook mouseHook = new MouseHook();
        /// <summary>
        /// 选择句柄
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butSelect_Click(object sender, EventArgs e)
        {
            mouseHook.OnMouseDownEvents += MouseHook_OnMouseDownEvents;
            mouseHook.OnMouseMove += MouseHook_OnMouseMove;
            mouseHook.SetHook();
        }

        private void MouseHook_OnMouseDownEvents(object sender, MouseEventArgs e)
        {
            Point p = new Point(e.X, e.Y);
            int hrp = WinHelper.GetHwnd(p);
            WinHelper.winIntPtr = hrp;
            mouseHook.OnMouseDownEvents -= MouseHook_OnMouseDownEvents;
            mouseHook.OnMouseMove -= MouseHook_OnMouseMove;
            mouseHook.UnHook();
            btnStart.Enabled = true;
        }

        private void MouseHook_OnMouseMove(object sender, MouseEventArgs e)
        {
            Point p = new Point(e.X, e.Y);
            int hrp = WinHelper.GetHwnd(p);
            txtName.Text = hrp.ToString();
        }

        /// <summary>
        /// 写入信息
        /// </summary>
        /// <param name="msg"></param>
        public void WriteMsg(string msg)
        {
            if (msg.Contains("interfaces"))
            {
                string interfaces = Data.GetEnumDescription<Data.GameInterface>(Data.IndexGameInterface.ToString());

                if (toolStrip1.InvokeRequired)
                {
                    toolStrip1.Invoke(new Action<string>((p) =>
                       {
                           laIndexInterface.Text = ($"{p}");
                       }), interfaces);

                }
                else
                    laIndexInterface.Text = ($"{interfaces}");
            }
            else
            {
                if (txtMsg.InvokeRequired)
                    txtMsg.Invoke(new Action<string>((p) =>
                    {
                        txtMsg.AppendText($"{p}\r\n");
                    }), msg);
                else
                    txtMsg.AppendText($"{msg}\r\n");

            }
        }



        /// <summary>
        /// 设置大小
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSetSize_Click(object sender, EventArgs e)
        {
            WinHelper.SetTopWindowSize((int)WNum.Value, (int)HNum.Value);
        }

        private void btnSetStyle_Click(object sender, EventArgs e)
        {
            WinHelper.MoveWindow((int)Xnum.Value, (int)Ynum.Value, (int)WNum.Value, (int)HNum.Value);
        }

        private void refreshTime_Tick(object sender, EventArgs e)
        {
            lbTimeNow.Text = DateTime.Now.ToString("G");
        }

        /// <summary>
        /// 选择模拟器 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            var value = (BindComboxEnumType<SimulatorType>)cbType.SelectedItem;
            Simulator.SetSimulator(value.Type);
            WNum.Value = ConfigData.Current.SimulatorSize.Width;
            HNum.Value = ConfigData.Current.SimulatorSize.Height;
        }
    }
}
